<template>
  <div>
    <el-button type="primary" style="margin-bottom: 15px"  @click="addDialogVisible = true"
      >添加角色</el-button
    >
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <template>
        <el-table :data="roleList" style="width: 100%" border stripe>
          <el-table-column type="expand">
              <template slot-scope="scope">
                  <el-row  :class="['bdbottom',i1===0?'bdtop':'','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
                      <!-- 渲染一级权限 -->
                      <el-col :span="5" >
                          <el-tag closable  @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag><i class="el-icon-caret-right"></i>
                      </el-col>
                      <!-- 渲染二级三级权限 -->
                      <el-col :span="19">
                          <el-row :class="[i2===0?'':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                              <el-col :span="6" ><el-tag closable type="success"  @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag><i class="el-icon-caret-right"></i></el-col>
                              
                              <el-col :span="18">
                                  <el-tag closable v-for="item3 in item2.children" :key="item3.id" type="warning" @close="removeRightById(scope.row,item3.id)" >{{item3.authName}}</el-tag>
                              </el-col>
                          </el-row>
                      </el-col>
                  </el-row>
                 
              </template>
               </el-table-column>
          <el-table-column type="index" label="#"> </el-table-column>
          <el-table-column prop="roleName" label="角色名称"> </el-table-column>
          <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-tooltip
                :enterable="false"
                effect="dark"
                content="编辑"
                placement="top"
              >
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
              </el-tooltip>

              <el-tooltip
                :enterable="false"
                effect="dark"
                content="删除"
                placement="top"
              >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeUserById(scope.row.id)"
                  >删除</el-button
                >
              </el-tooltip>
              <el-tooltip
                :enterable="false"
                effect="dark"
                content="分配权限"
                placement="top"
              >
                <el-button type="warning" icon="el-icon-setting" size="mini"
                   @click="showSetRightDialog(scope.row)">分配权限</el-button
                >
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="30%"
        @close="addDialogClose"
      >
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="90px"
        >
          <el-form-item label="角色名" prop="roleName">
            <el-input v-model="addForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色信息" prop="roleDesc">
            <el-input v-model="addForm.roleDesc"></el-input>
          </el-form-item>
          
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        title="修改角色"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClose"
      >
        <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
          label-width="90px"
        >
          <el-form-item label="角色名" prop="roleName">
            <el-input v-model="editForm.roleName" ></el-input>
          </el-form-item>
          <el-form-item label="角色详情" prop="roleDesc">
            <el-input v-model="editForm.roleDesc"></el-input>
          </el-form-item>
          
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog
  title="分配权限"
  :visible.sync="setRightDialogVisible"
  width="50%"
  @close="setRightDialogClosed"
  >
  <el-tree :data="rightsList" :props="treeProps" show-checkbox node-key="id" :default-expand-all="true" :default-checked-keys="defkeys" ref="treeRef"></el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRightDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
</el-dialog>

  </div>
</template>

<script>
export default {
   
  created() {
    this.getRoleList();
  },
  data() {
    return {
        roleId:'',
        defkeys:[],
        treeProps:{
            children:'children',
            label:'authName'
        },
        rightsList:[],
        setRightDialogVisible:false,
      editFormRules: {
        roleName: [
          {
            required: true,
            message: "请输入角色名",
            trigger: "blur",
          },
          {
            min: 1,
            max: 10,
            message: "长度在 1 到 10 个字符",
            trigger: "blur",
          },
        ],
        roleDesc: [
          {
            required: true,
            message: "请输入描述",
            trigger: "blur",
          },
          
        ],
      },
      addFormRules: {
        roleName: [
          {
            required: true,
            message: "请输入角色名",
            trigger: "blur",
          },
          {
            min: 1,
            max: 10,
            message: "长度在 1 到 10 个字符",
            trigger: "blur",
          },
        ],
        roleDesc: [
          {
            required: true,
            message: "请输入描述",
            trigger: "blur",
          },
          
        ],
        
      },
      editForm: {
        id: 0,
        roleName: "",
        roleDesc: "",
        
      },
      addForm: {
        roleName: "",
        roleDesc: "",
        
      },
      addDialogVisible: false,
      editDialogVisible: false,
      roleList: [],
    };
  },
  methods: {
     
    editDialogClose() {
      this.$refs.editFormRef.resetFields();
    },
    addDialogClose() {
      this.$refs.addFormRef.resetFields();
    },
     addUser() {
      this.$refs.addFormRef.validate((valid) => {
        if (valid) {
          this.$http.post("roles", this.addForm).then((res) => {
            console.log(res.data);
            if (res.data.meta.status === 201) {
              this.$message.success("添加角色成功");
              this.getRoleList();
            } else {
              this.$message.error("添加角色失败");
            }
          });
        } else {
          return this.$message.error("表单验证失败");
        }
      });
      this.addDialogVisible = false;
      
    },
    editUser() {
      console.log(this.editForm)
      this.$refs.editFormRef.validate((valid) => {
        if (valid) {
        this.$http.put( `roles/${this.editForm.id}`,{
          roleName:this.editForm.roleName,
          roleDesc:this.editForm.roleDesc
        }).then(res=>{
          if(res.data.meta.status===200){
             this.$message.success("修改角色信息成功")
            this.getRoleList()
            
          }else
          {
            this.$message.error("修改角色信息失败")
          }
        })
        } else {
          return this.$message.error("表单验证失败");
        }
      });
      
      this.editDialogVisible=false
    },
    removeUserById(id){
        console.log(id)
      
       this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
         
          
          this.$http.delete(`roles/${id}`).then(res=>{
            console.log(res.data)
            if(res.data.meta.status===200){
               this.$message({
            type: 'success',
            message: '删除成功!',
            
          })
          this.getRoleList()
            }
            else
            {
              this.$message.error("删除失败")
            }
          })
         
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
         
    },
    getRoleList() {
        
      this.$http.get(`roles`).then((res) => {
        if (res.data.meta.status === 200) {
          this.roleList = res.data.data;
        } else {
          this.$message.console.error("获取失败");
        }
      });
    },
    showEditDialog(userInfo) {
      // console.log(1)
      this.editForm.id = userInfo.id;
      
      this.editForm.roleName = userInfo.roleName;
      this.editForm.roleDesc = userInfo.roleDesc;
      
      this.editDialogVisible = true;
    },
    removeRightById(role,rightId){
        this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(()=>{
            this.$http.delete(`roles/${role.id}/rights/${rightId}`).then(res=>{
                if(res.data.meta.status===200){
                    // console.log(111)
                    this.$message.success("删除成功")
                    role.children=res.data.data
                }else{
                    return this.$message.error("删除失败")
                }
            })
        }

        ).catch(()=>{
            
            this.$message.info("取消删除")
        })

    },
    showSetRightDialog(role){
        this.roleId=role.id
        this.setRightDialogVisible=true
        this.$http.get(`rights/tree`).then(res=>{
            if(res.data.meta.status===200){
                this.rightsList=res.data.data
                // console.log(this.rightsList)
                // console.log(role)
        // console.log(this.roleList)
        // 递归调用判断每一层权限中是否有children节点
        this.getLeafKeys(role,this.defkeys)
            }else{
                this.$message.error("请求失败")
            }
        })
        
        //  var list=[]
        //   for( i=0; i<role.children.children.children.length;i++){
        //       list.push(role.children.children.children.id)
        //   }
        //   this.defkeys=list
    },
    getLeafKeys(node,arr){
        if(!node.children){
            arr.push(node.id)
            return
        }
       console.log(node)
        node.children.forEach(item=>{
            this.getLeafKeys(item,arr)
        })
    },
    setRightDialogClosed(){
        this.defkeys=[]
    },
    allotRights(){
        const keys=[
            ...this.$refs.treeRef.getCheckedKeys(),
            ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        const idStr=keys.join(',')
        this.$http.post(`roles/${this.roleId}/rights`,{
            rids:idStr
        }).then(res=>{
            console.log(res)
            if(res.data.meta.status===200){
                this.$message.success("分配权限成功")
                this.getRoleList()
                this.setRightDialogVisible=false
            }
            else{
                this.$message.error("分配权限失败")
                this.setRightDialogVisible=false
            }
        })
        
    }
    //   computedType(level){
    //     if(level==='0'){
    //         return

    //     }
    //     else if(level==='1'){
    //         return "success"
    //     }
    //     else if(level==='2'){
    //         return "warning"
    //     }
    // }
  },
  computed: {},
};
</script>


<style lang="less" scoped>
.el-tag{
    margin: 7px;
}
.bdtop{
    border-top: 1px solid #eee;
}
.bdbottom{
     border-bottom: 1px solid #eee;

}
.vcenter{
    display: flex;
    align-items: center;
}
</style>
